﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBService;


public partial class EditCompany : System.Web.UI.Page, ICallbackEventHandler
{
    int CompanyID;
    ModelAdapter ma = new ModelAdapter();
    string callBackData;
    Company Comp;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (int.TryParse((string)Request.QueryString["id"], out CompanyID))
        {
            Comp = ma.GetCompanies(CompanyID).Single();
            if (!IsPostBack)
            {
                LogoImg.Src = "upload/" + Comp.Logo;
                CompanyName.Value = Comp.Name;
                Address.Value = Comp.Address;
                Phone.Value = Comp.Phone;
                Website.Value = Comp.Website;

                Map.Value = Comp.Map;
                IsWifi.Checked = Comp.WiFi == true;
                IsOpenAir.Checked = Comp.OpenAir == true;
                Monday.Checked = Comp.Monday == true;
                Thuesday.Checked = Comp.Tuesday == true;
                Wednesday.Checked = Comp.Wednesday == true;
                Thursday.Checked = Comp.Thursday == true;
                Friday.Checked = Comp.Friday == true;
                Saturday.Checked = Comp.Saturday == true;
                Sunday.Checked = Comp.Sunday == true;

                WorkHourFrom.Value = Comp.WorkStartHour.HasValue ? Comp.WorkStartHour.Value.ToString() : "";
                WorkHourTo.Value = Comp.WorkEndHour.HasValue ? Comp.WorkEndHour.Value.ToString() : "";

                PriceFrom.Value = Comp.PriceFrom.HasValue ? Comp.PriceFrom.Value.ToString() : "";
                PriceTo.Value = Comp.PriceTo.HasValue ? Comp.PriceTo.Value.ToString() : "";

                Gel.Checked = Comp.GEL == true;
                USD.Checked = Comp.USD == true;
                Eur.Checked = Comp.EUR == true;

                if (Comp.Gallery != null && Comp.Gallery.GalleryFiles != null && Comp.Gallery.GalleryFiles.Count > 0)
                {
                    foreach (var gimg in Comp.Gallery.GalleryFiles)
                    {
                        LitGalleryImage.Text += "<div style=\"float: left; margin-left: 20px;\">" +
                                                    "<img width=\"100px\" height=\"100px\" src=\"upload/" + gimg.File.FilePath + "\" />" +
                                                    "<a imgid=\"" + gimg.File.FileID + "\" class=\"deletegalleryimage\" href=\"upload/" + gimg.File.FilePath + "\">" +
                                                        "<img src=\"images/delete.jpg\" />" +
                                                    "</a>" +
                                               "</div>";
                    }
                }
                else
                {
                    LitGalleryImage.Text = "სურათები არ არის...";
                }
                if (Comp.CompanyCategories != null && Comp.CompanyCategories.Count > 0)
                {
                    foreach (var compCat in Comp.CompanyCategories)
                    {
                        LitCategoryItem.Text += "<li><a class=\"DeleteFromCategory editcat\" href=\"#\" cid=\"" + compCat.Category.CategoryID + "\">" + compCat.Category.Title + "</a><b>X</b></li>";
                    }
                }



                var cats = ma.GetCategoreis(null);
                foreach (var cat in cats)
                {
                    LitCategoryOption.Text += "<option value=\"" + cat.CategoryID + "\">" + cat.Title + "</option>";
                }
            }

            #region callback scripts
            ClientScriptManager cm = Page.ClientScript;
            String cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");
            String callbackScript = "function CallServer(arg, context) {" + cbReference + "; }";
            cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
            #endregion
        }
        else
        {
            Response.Redirect("default.aspx");
        }
    }

    protected void OnSubmit(object sender, EventArgs e)
    {
        try
        {
            string Logo = "";
            if (UploadLogo.HasFile && string.IsNullOrEmpty(Comp.Logo))
            {
                Logo = Guid.NewGuid().ToString().Substring(0, 10) + System.IO.Path.GetFileName(UploadLogo.FileName);
            }
            else
            {
                Logo = Comp.Logo;
            }




            List<string> images = new List<string>();
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hpf.ContentLength > 0
                    && new string[] { ".gif", ".png", ".jpeg", ".jpg" }.Contains(System.IO.Path.GetExtension(hpf.FileName).ToLower())
                    && System.IO.Path.GetFileName(hpf.FileName) != System.IO.Path.GetFileName(UploadLogo.FileName))
                {
                    string img = Guid.NewGuid().ToString().Substring(0, 10) +
                      System.IO.Path.GetFileName(hpf.FileName);
                    images.Add(img);
                    hpf.SaveAs(Server.MapPath("upload") + "\\" + img);
                }
            }

            List<int> categories = new List<int>();
            if (!String.IsNullOrEmpty(HidnField.Value))
            {
                foreach (var cat in HidnField.Value.Split('|'))
                {
                    if (!String.IsNullOrEmpty(cat))
                    {
                        categories.Add(int.Parse(cat));
                    }
                }
            }

            short workFrom;
            short workTo;
            if (!short.TryParse(WorkHourFrom.Value, out workFrom))
            {
                workFrom = 10;
            }
            if (!short.TryParse(WorkHourTo.Value, out workTo))
            {
                workTo = 18;
            }


            int priceFrom;
            int priceTo;
            if (!int.TryParse(PriceFrom.Value, out priceFrom))
            {
                priceFrom = 10;
            }
            if (!int.TryParse(PriceTo.Value, out priceTo))
            {
                priceTo = 18;
            }

            ModelAdapter adapter = new ModelAdapter();
            adapter.CompanyAction(CompanyID, Logo, CompanyName.Value, Address.Value,Map.Value, Phone.Value.ToString(),
                                  Website.Value.ToString(), IsWifi.Checked, IsOpenAir.Checked, Monday.Checked,
                                  Thuesday.Checked, Wednesday.Checked, Thursday.Checked, Friday.Checked,
                                  Saturday.Checked, Sunday.Checked, workFrom, workTo,
                                  priceFrom, priceTo, Gel.Checked, USD.Checked, Eur.Checked,
                                  null, null, null, null, categories, images, null);

            if (UploadLogo.HasFile)
            {
                UploadLogo.SaveAs(Server.MapPath("upload") + "\\" + Logo);
            }

            Response.Redirect(Request.Url.OriginalString);
            //Script.Text = "<script>alert('თქვენ წარმატებით დარეგისტრირდით!'); window.location = 'default.aspx';</script>";
        }
        catch (Exception ex)
        {
            Script.Text = "<script>alert('დაფიქსირდა შეცდომა!..');</script>";
        }
        //Response.Write(HidnField.Value);
    }


    string ICallbackEventHandler.GetCallbackResult()
    {
        return callBackData;
    }

    void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
    {
        try
        {
            var parts = eventArgument.Split('|');
            if (String.IsNullOrEmpty(eventArgument))
            {
                callBackData = "Error|დაფიქსირდა შეცდომა";
                return;
            }
            callBackData = "Success|";

            switch (parts[0])
            {
                case "DeleteGalleryImage":
                    {
                        System.IO.File.Delete(Server.MapPath(parts[2]));
                        int FileID = int.Parse(parts[1]);
                        var resu = ma.DeleteFileByID(FileID);
                        callBackData += resu;
                        break;
                    }
                case "DeleteCategory":
                    {
                        int CatgryID = int.Parse(parts[1]);
                        var resu = ma.CompanyCategoryDelete(CatgryID, CompanyID);
                        callBackData += resu;
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }
        catch (Exception ex)
        {
            callBackData = "Error|დაფიქსირდა შეცდომა";
            return;
        }
    }


}
